<?php
/**
 * CK框架 IP地址类
 * @author wujibing<283109896@qq.com>
 * @version   3.0
 * @category   CkFrameWork
 * @package  CkFrameWork
 * @subpackage lib
 */
class ipAddress
{
	/**
	 * 获取客户端IP
	 * @return string
	 */
	public static function getIp()
	{
		$onlineip = '';
		if(isset($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] && strcasecmp($_SERVER['HTTP_CLIENT_IP'], 'unknown'))
		{
			$onlineip = $_SERVER['HTTP_CLIENT_IP'];
		} elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], 'unknown'))
		{
			$onlineip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown'))
		{
			$onlineip = $_SERVER['REMOTE_ADDR'];
		}
		preg_match('$[\d\.]{7,15}$', $onlineip, $onlineipMatches);
		$onlineip = isset($onlineipMatches[0]) && $onlineipMatches[0]? $onlineipMatches[0] : 0;
		//如果没有获取到IP 直接抛出错误
		return $onlineip;
	}
	/**
	 * IP格式化
	 * @param string $ip
	 * @return string
	 */
	public static function ipForamt($ip)
	{
		$onlineip = explode('.',$ip);
		if(count($onlineip) < 4)
		{
			return 0;
		}
		$newIp = '';
		foreach ($onlineip as $v)
		{
			$newIp .= sprintf('%03d',$v);
		}
		return $newIp;
	}
	/**
	 * 过滤IP
	 * 当$ip属于过滤规则内，则不允许访问
	 * @param string $ip ip地址
	 * @package string $ipFilter过滤规则
	 * $ipFilter支持三种过滤
	 * 1、192.168.1.0-192.168.255.255 过滤网段
	 * 2、192.168.1.0/16 过滤1-16的IP
	 * 3、192.168.1.122 直接过滤IP
	 * $ipFilter支持多行匹配 \r\n
	 * 例如：
	 * 192.168.1.0-192.168.255.255
	 * 121.154.26.4
	 * @return boolean
	 */
	public static function ipFilter($ip,$ipFilter)
	{
	    $ip = trim($ip);
	    $ipFilterArray = explode("\r\n", $ipFilter);
	    $result = false;
	    $ip2long = ip2long($ip);
	    if($ipFilter) foreach ($ipFilterArray as $value)
	    {
	        $value = trim($value);
	        //匹配IP网段192.168.1.0-192.168.255.255
	        if (($pos = strpos($value, '-'))!== false)
	        {
	            $from = ip2long(trim(substr($value, 0, $pos)));
	            $to = ip2long(trim(substr($value, $pos+1)));
	            $result = ($ip2long >= $from && $ip2long <= $to);
	        //匹配192.168.1.0/16
	        } else if (strpos($value,'/')!== false)
	        {
	            list ($net, $mask) = explode ('/', $value);
	            $net2long = ip2long($net);
	            
	            $result = ($ip2long >= $net2long && $ip2long <= $net2long+$mask);
	        //匹配IP
	        } else
	        {
	            $result = $value === $ip;
	        }
	        if($result)
	        {
	            return true;
	        }
	    }
	    return false;
	}
}
